<template>
  <div class="app-container agricultural-detail">
    <el-page-header content="返回农产品列表" @back="$router.go(-1)" />

    <el-card v-loading="loading" class="detail-card">
      <!-- 左右布局容器 -->
      <div class="detail-layout">
        <!-- 左侧图片区域 -->
        <div class="left-column">
          <div v-if="parsedImages.length" class="image-container">
            <!-- 主图显示 -->
            <div class="main-image" v-for="(img, index) in parsedImages" :key="index">
              <image-preview
                :src="img"
                :width="'100%'"
                :height="400"
                @click="viewImage(img)"
              >
                <img
                  :src="img"
                  class="detail-image"
                  alt="农产品图片"
                >
              </image-preview>
            </div>

            <!-- 缩略图 -->
            <div class="thumbnail-container">
              <div
                v-for="(img, index) in parsedImages"
                :key="index"
                class="thumbnail"
                :class="{ active: currentIndex === index }"
                @click="switchImage(index)"
              >
                <img :src="getImageUrl(img)" :alt="`农产品图片 ${index+1}`">
              </div>
            </div>
          </div>
        </div>

        <!-- 右侧详情区域 -->
        <div class="right-column">
          <div class="detail-content">
            <h1 class="title">{{ agricultural.name }}</h1>

            <div class="price-section">
              <div class="price-info">
                <i class="el-icon-money"></i>
                <span class="price">¥{{ agricultural.price }}</span>
                <span class="unit"> / {{ agricultural.unit }}</span>
              </div>
            </div>

            <div class="meta-list">
              <div class="meta-item">
                <span class="meta-label">分类：</span>
                <el-tag type="primary">{{ agricultural.type || '未分类' }}</el-tag>
              </div>

              <div class="meta-item">
                <span class="meta-label">产地：</span>
                <span class="meta-value">
                  <i class="el-icon-location"></i>
                  {{ agricultural.origin || '未指定产地' }}
                </span>
              </div>

              <div class="meta-item">
                <span class="meta-label">商店：</span>
                <span class="meta-value">
                  <i class="el-icon-shopping-cart"></i>
                  {{ deptName || '未指定商店' }}
                </span>
              </div>

              <div class="meta-item">
                <span class="meta-label">上架时间：</span>
                <span class="meta-value">
                  <i class="el-icon-time"></i>
                  {{ formatDate(agricultural.createTime) || '未记录上架时间' }}
                </span>
              </div>
            </div>

            <el-divider content-position="left"><h3>农产品简介</h3></el-divider>
            <div class="intro-content" v-html="agricultural.description || '暂无农产品简介'"></div>

            <el-divider content-position="left"><h3>产品规格</h3></el-divider>
            <div class="specs-content">
              <div class="spec-item" v-if="agricultural.specification">
                <span class="spec-label">规格：</span>
                <span class="spec-value">{{ agricultural.specification }}</span>
              </div>
              <div class="spec-item" v-if="agricultural.unit">
                <span class="spec-label">单位：</span>
                <span class="spec-value">{{ agricultural.unit }}</span>
              </div>
              <div class="spec-item" v-if="agricultural.weight">
                <span class="spec-label">重量：</span>
                <span class="spec-value">{{ agricultural.weight }}</span>
              </div>
              <div class="spec-item" v-if="agricultural.shelfLife">
                <span class="spec-label">保质期：</span>
                <span class="spec-value">{{ agricultural.shelfLife || '未标注' }}</span>
              </div>
              <div class="spec-item" v-if="agricultural.productionCycle">
                <span class="spec-label">生产周期：</span>
                <span class="spec-value">{{ agricultural.productionCycle || '未标注' }}</span>
              </div>
            </div>

            <el-divider content-position="left"><h3>产地信息</h3></el-divider>
            <div class="origin-content" v-html="agricultural.origin || '暂无产地详细信息'"></div>

            <!-- 新增：购物车选项 -->
            <el-divider content-position="left"><h3>购买选项</h3></el-divider>
            <div class="cart-section">
              <div class="quantity-selector">
                <span class="label">购买数量：</span>
                <el-input-number
                  v-model="quantity"
                  :min="1"
                  :max="99"
                  :step="1"
                  size="large"
                  @change="calculateTotalPrice"
                ></el-input-number>
                <span class="total-price">
                  小计：<span class="price">¥{{ totalPrice }}</span>
                </span>
              </div>

              <div class="action-buttons">
                <el-button
                  type="primary"
                  size="large"
                  @click="addToCart"
                  :loading="addingToCart"
                >
                  <i class="el-icon-shopping-cart-2"></i> 加入购物车
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getAgricultural } from "@/api/system/agricultural";
import { listDepts } from "@/api/system/depts";
import imagePreview from "@/components/ImagePreview";
import { addOrder } from "@/api/system/order"; // 引入订单API

export default {
  name: "AgriculturalDetail",
  components: {
    imagePreview
  },
  data() {
    return {
      loading: true,
      agricultural: {},
      parsedImages: [], // 处理后的完整图片URL数组
      currentIndex: 0, // 当前显示的图片索引
      baseUrl: process.env["VUE_APP_BASE_API"] || "", // 图片服务器地址
      deptName: "未指定商店", // 商店名称
      depts: {}, // 部门映射表
      // 新增购物车相关数据
      quantity: 1,
      totalPrice: 0,
      addingToCart: false
    };
  },
  watch: {
    $route: {
      handler: function(route) {
        this.loadAgriculturalDetail(route.params.id);
      },
      immediate: true
    }
  },
  computed: {
    // 检查用户是否已登录
    isLoggedIn() {
      return this.$store.state.token;
    },
      userId() {
    return this.$store.state.id;
      }
  },
  methods: {
    // 加载农产品详情
    loadAgriculturalDetail(id) {
      this.loading = true;
      this.fetchData(id);
    },

    // 获取农产品详情数据
    async fetchData(id) {
      try {
        // 获取农产品详情
        const agriculturalResponse = await getAgricultural(id);
        this.agricultural = agriculturalResponse.data || {};

        // 获取部门信息用于显示商店名称
        const deptResponse = await this.getDeptData();
        this.depts = deptResponse;
        this.deptName = this.depts[this.agricultural.deptId] || "未指定商店";
        this.parseImages(); // 解析图片URL
        this.calculateTotalPrice(); // 初始化总价
      } catch (error) {
        console.error("获取农产品详情失败:", error);
        this.$message.error("获取农产品详情失败，请重试");
      } finally {
        this.loading = false;
      }
    },

    // 获取部门数据
    async getDeptData() {
      try {
        const deptResponse = await listDepts({ pageNum: 1, pageSize: 1000 });
        let deptList = [];

        if (deptResponse.data && Array.isArray(deptResponse.data)) {
          deptList = deptResponse.data;
        } else if (deptResponse.rows && Array.isArray(deptResponse.rows)) {
          deptList = deptResponse.rows;
        } else if (Array.isArray(deptResponse)) {
          deptList = deptResponse;
        } else {
          deptList = [];
        }

        if (Array.isArray(deptList)) {
          return deptList.reduce((map, dept) => {
            const deptId = Number(dept.deptId);
            const deptName = dept.deptName || '未知部门';
            map[deptId] = deptName;
            return map;
          }, {});
        } else {
          console.warn('部门数据不是数组，无法构建映射:', deptList);
          return {};
        }
      } catch (error) {
        console.error("获取部门数据失败:", error);
        return {};
      }
    },

    // 解析图片URL
    parseImages() {
      // 处理逗号分隔的图片URL字符串
      const rawUrls = this.agricultural.imageUrl || "";
      this.parsedImages = rawUrls
        .split(",")
        .map(url => url.trim())
        .filter(url => url);

    },

    // 统一图片URL处理（开发/生产环境适配）
    getImageUrl(url) {
      if (!url){
        console.log('传进来的图片路径是null')
        return "";
      }
      // 若URL已包含完整协议（http/https），直接返回
      if (url.startsWith('http://') || url.startsWith('https://')) {
        return url;
      }
      // 否则拼接基础路径（处理相对路径）
      // 避免重复添加斜杠（如baseUrl以/结尾，url以/开头时只保留一个）
      const finalUrl =  this.baseUrl + (this.baseUrl.endsWith('/') ? '' : '/') +
          (url.startsWith('/') ? url.substring(1) : url);
      console.log("传进来的图片最终url是：" + finalUrl);
      return finalUrl;
    },

    // 查看大图
    viewImage(url) {
      this.$refs.imagePreview.showLargeImage(url);
    },

    // 切换图片
    switchImage(index) {
      this.currentIndex = index;
    },

    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return date.toLocaleDateString() + ' ' + date.toLocaleTimeString();
    },

    // 计算总价
    calculateTotalPrice() {
      // 确保总价始终显示两位小数
      this.totalPrice = (this.agricultural.price || 0) * this.quantity;
      this.totalPrice = parseFloat(this.totalPrice.toFixed(2));
    },

    // 添加到购物车
    async addToCart() {
      // 检查是否登录
      if (!this.isLoggedIn) {
        this.$message.warning("请先登录再添加购物车");
        return this.$router.push({ name: "Login" });
      }

      // 检查产品数据是否加载完成
      if (!this.agricultural.id) {
        this.$message.error("产品数据未加载完成，请稍后再试");
        return;
      }

      // 显示加载状态
      this.addingToCart = true;

      try {
        // 准备订单数据
        const orderData = {
          userId: this.userId, // 从store中获取用户ID
          productId: this.agricultural.id,
          productType: '农产品',
          deptId: this.agricultural.deptId,
          quantity: this.quantity,
          status: '待支付'
        };
          console.log("提交的订单数据：", orderData);
        // 调用API添加订单
        const response = await addOrder(orderData);

        if (response.code === 200) {
          this.$message.success("已成功添加到购物车");
          // 可选：通知购物车数量更新
          this.$store.dispatch('cart/updateCartCount');
        } else {
          this.$message.error(response.msg || "添加购物车失败");
        }
      } catch (error) {
        console.error("添加购物车失败:", error);
        this.$message.error("添加购物车失败，请稍后再试");
      } finally {
        this.addingToCart = false;
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.agricultural-detail {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;

  .detail-card {
    margin-top: 20px;
    overflow: hidden;

    .detail-layout {
      display: flex;
      gap: 30px;
    }

    // 左侧图片区域
    .left-column {
      flex: 0 0 500px;

      .image-container {
        width: 100%;

        .main-image {
          width: 100%;
          border-radius: 8px;
          overflow: hidden;
          box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

          .detail-image {
            width: 100%;
            height: 400px;
            object-fit: cover;
            transition: transform 0.3s ease;

            &:hover {
              transform: scale(1.02);
            }
          }
        }

        .thumbnail-container {
          display: flex;
          gap: 10px;
          margin-top: 15px;
          overflow-x: auto;
          padding-bottom: 5px;

          .thumbnail {
            width: 80px;
            height: 60px;
            border-radius: 4px;
            overflow: hidden;
            cursor: pointer;
            border: 2px solid transparent;
            transition: all 0.2s ease;

            &.active {
              border-color: #409EFF;
              box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
            }

            img {
              width: 100%;
              height: 100%;
              object-fit: cover;
            }

            &:hover {
              transform: translateY(-2px);
            }
          }
        }
      }
    }

    // 右侧详情区域
    .right-column {
      flex: 1;
      padding: 10px 0;

      .detail-content {
        .title {
          font-size: 26px;
          color: #2c3e50;
          margin-bottom: 20px;
          line-height: 1.3;
        }

        .price-section {
          margin-bottom: 25px;
          padding-bottom: 15px;
          border-bottom: 1px solid #eee;

          .price-info {
            display: flex;
            align-items: center;

            .el-icon-money {
              color: #e74c3c;
              margin-right: 8px;
              font-size: 20px;
            }

            .price {
              font-size: 28px;
              font-weight: bold;
              color: #e74c3c;
              margin-right: 10px;
            }

            .unit {
              color: #666;
              font-size: 16px;
            }
          }
        }

        .meta-list {
          margin-bottom: 25px;
          padding-bottom: 15px;
          border-bottom: 1px solid #eee;

          .meta-item {
            display: flex;
            align-items: center;
            margin-bottom: 12px;

            .meta-label {
              min-width: 80px;
              color: #909399;
              font-weight: 500;
            }

            .meta-value {
              color: #333;
              display: flex;
              align-items: center;

              i {
                margin-right: 5px;
                color: #666;
              }
            }
          }
        }

        .intro-content, .specs-content, .origin-content {
          font-size: 16px;
          line-height: 1.8;
          color: #555;
          margin: 15px 0 25px;
        }

        .specs-content {
          .spec-item {
            display: flex;
            margin-bottom: 10px;

            .spec-label {
              min-width: 80px;
              color: #909399;
              font-weight: 500;
            }

            .spec-value {
              color: #333;
            }
          }
        }

        // 新增：购物车区域样式
        .cart-section {
          margin-top: 30px;

          .quantity-selector {
            display: flex;
            align-items: center;
            margin-bottom: 20px;

            .label {
              margin-right: 15px;
              font-size: 16px;
              color: #555;
            }

            .el-input-number {
              width: 150px;
            }

            .total-price {
              margin-left: 30px;
              font-size: 18px;

              .price {
                color: #e74c3c;
                font-weight: bold;
                margin-left: 5px;
              }
            }
          }

          .action-buttons {
            .el-button {
              padding: 12px 30px;
              font-size: 16px;
            }
          }
        }
      }
    }
  }
}

// 响应式设计
@media (max-width: 1024px) {
  .agricultural-detail {
    .detail-card {
      .detail-layout {
        flex-direction: column;
        gap: 20px;
      }

      .left-column {
        flex: none;
        width: 100%;

        .image-container {
          .main-image {
            .detail-image {
              height: 350px;
            }
          }
        }
      }
    }
  }
}

@media (max-width: 768px) {
  .agricultural-detail {
    padding: 15px;

    .detail-card {
      .left-column {
        .image-container {
          .main-image {
            .detail-image {
              height: 250px;
            }
          }

          .thumbnail-container {
            .thumbnail {
              width: 70px;
              height: 50px;
            }
          }
        }
      }

      .right-column {
        .detail-content {
          .title {
            font-size: 22px;
          }

          .price-section {
            .price-info {
              .price {
                font-size: 24px;
              }
            }
          }

          .cart-section {
            .quantity-selector {
              flex-direction: column;
              align-items: flex-start;

              .label, .el-input-number, .total-price {
                margin-bottom: 15px;
              }
            }
          }
        }
      }
    }
  }
}
</style>
